<script setup>
import { onMounted, nextTick, ref, reactive, watch } from 'vue'
import { User, Unlock, View, Hide } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import identify from '../components/mylement/identify.vue'
import CryptoJS from "crypto-js";
import { encrypt, decrypt } from '@/components/utils/tool.js'
import { userInfo } from './userInfo.js'
import provider from '../stores/provider'

const router = useRouter()

const urlGo = import.meta.env.VITE_backurl_go

// // 十六位十六进制数作为密钥
// const SECRET_KEY = CryptoJS.enc.Utf8.parse("91234567890123456789012345678901");
// // 不使用iv偏移量
// const SECRET_IV = CryptoJS.enc.Utf8.parse("91234567890123456789012345678901");
// function encrypt(data) {
//   if (typeof data === "object") {
//     try {
//       // eslint-disable-next-line no-param-reassign
//       data = JSON.stringify(data);
//     } catch (error) {
//       console.log("encrypt error:", error);
//     }
//   }
//   const dataHex = CryptoJS.enc.Utf8.parse(data);
//   const encrypted = CryptoJS.AES.encrypt(dataHex, SECRET_KEY, {
//     iv: SECRET_IV,
//     mode: CryptoJS.mode.CBC,
//     padding: CryptoJS.pad.Pkcs7
//   });
//   return encrypted.ciphertext.toString();
// }
// function decrypt(data) {
//   const encryptedHexStr = CryptoJS.enc.Hex.parse(data);
//   const str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
//   const decrypt = CryptoJS.AES.decrypt(str, SECRET_KEY, {
//     iv: SECRET_IV,
//     mode: CryptoJS.mode.CBC,
//     padding: CryptoJS.pad.Pkcs7
//   });
//   const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
//   return decryptedStr.toString();
// }

// onMounted(() => {

//   // 加密
//   let plaintext = "Hello, world!";
//   const ciphertext = encrypt(plaintext);
//   console.log("ciphertext:", ciphertext);
//   // 解密
//   const decryptedStr = decrypt(ciphertext);
//   console.log("decryptedStr:", decryptedStr);

// })

const isPass = ref(false),
  bySty = reactive({
    backgroundImage: 'url(./img/by_zuo.png), url(./img/by_you.png)',
  });
const passBlur = () => {
  isPass.value = false
},
  passFocus = () => {
    isPass.value = true
    // 强制英文输入法
    // 
  };

const isSee = ref(false)
const seeClick = (e) => {
  // 阻止冒泡
  e.stopPropagation()
  isSee.value = !isSee.value
}

const form = reactive({
  username: '',
  password: ''
})

// const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/

// 检验密码强度，至少包含数字和字母。长度8-16位
const reg = /^(?=.*[a-zA-Z])(?=.*\d)[^]{8,16}$/

const handleLogin = () => {
  if (codeValue.value != identifyCode.value) {
    ElMessage.error('验证码错误')
    refreshCode()
    return
  }
  let passwordJm = encrypt(form.password)
  axios({
    method: 'post',
    url: urlGo + '/login',
    data: {
      username: form.username,
      password: passwordJm
    },
  })
    .then(res => {
      if (res.data.code == 500) {
        ElMessage.error(res.data.message)
      } else {
        userInfo.value = res.data.data
        ElMessage.success(res.data.message)
        // let isAdmin = res.data.data?.role?.find(v => v.roleKey == 'admin')
        // console.log(isAdmin);forecast
        let isAdmin = false
        res.data.data?.role?.forEach(role => {
          role.right.forEach(right => {
            if (right.router.includes('forecast')) {
              isAdmin = true
            }
          })
        })
        router.push('/home')
        sessionStorage.setItem('userId', res.data.data.token)
      }
    })
    .catch(err => {
      ElMessage.error(err)
    })
},
  handleRegister = () => {
    if (codeValue.value != identifyCode.value) {
      ElMessage.error('验证码错误')
      refreshCode()
      return
    }
    // 用户名和密码不能为空
    if (!form.username || !form.password) {
      ElMessage.error('用户名和密码不能为空')
      return
    }
    // 密码必须包含数字和字母。长度8-16位
    if (!reg.test(form.password)) {
      ElMessage.error('密码必须包含数字和字母。长度8-16位')
      return
    }
    let passwordJm = encrypt(form.password)

    axios({
      method: 'post',
      url: urlGo + '/register',
      data: {
        username: form.username,
        password: passwordJm
      }
    })
      .then(res => {
        if (res.data.code == 500) {
          ElMessage.error(res.data.message)
        } else {
          ElMessage.success(res.data.message)
        }
      })
      .catch(err => {
        ElMessage.error(err)
      })
  }

const identifyCode = ref('3321'),
  codeValue = ref('')
const refreshCode = () => {
  identifyCode.value = Math.floor(Math.random() * (9999 - 1000 + 1) + 1000).toString()
}
refreshCode()

const validateInput = () => {
  // 只能输入数字，英文和符号
  form.password = form.password.replace(/[^\w\.\/]/ig, '')
}

const activeSty = {
  color: 'var(--el-color-primary)',
  borderBottom: '2px solid var(--el-color-primary)'
}
const activeIdx = ref(0)
const handleSelect = (e) => {
  activeIdx.value = e
  form.username = ''
  form.password = ''
  codeValue.value = ''
  refreshCode()

}

</script>

<template>
  <div class="LoginView">
    <div id="login_left"></div>
    <div id="login_right">
      <div id="login_item">
        <div class="login_welcom">
          <span>航运大数据数字化</span>
          <br/>
          <span>管理与分析平台</span>
          <!-- /航运大数据数字化
管理与分析平台 -->
        </div>
        <div class="login_change">
          <div :style="activeIdx == 0 ? activeSty : ''" class="change_item" @click="handleSelect(0)">登录</div>
          <div :style="activeIdx == 1 ? activeSty : ''" class="change_item" @click="handleSelect(1)">注册</div>
        </div>
        <div class="login_form">
          <div class="form_item">
            <el-input :prefix-icon="User" class="login_input" v-model="form.username" placeholder=""
              size="normal"></el-input>
          </div>
          <div class="form_item">
            <el-input :prefix-icon="Unlock" :type="isSee ? 'text' : 'password'" class="login_input"
              v-model="form.password" placeholder="" size="normal" @blur="passBlur" @focus="passFocus"
              @input="validateInput">
              <template #suffix>
                <div @click="seeClick" style="cursor: pointer;">
                  <el-icon v-if="isSee">
                    <View />
                  </el-icon>
                  <el-icon v-else>
                    <Hide />
                  </el-icon>
                </div>
              </template>
            </el-input>
          </div>
          <div class="form_item">
            <el-row :gutter="5">
              <el-col :span="10" :offset="0">
                <identify :identifyCode="identifyCode" @click="refreshCode" />
              </el-col>
              <el-col :span="14" :offset="0">
                <el-input class="login_input" v-model="codeValue" placeholder="输入验证码"></el-input>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="login_login">
          <el-button type="primary" round @click="handleLogin" v-if="activeIdx == 0">登录</el-button>
          <el-button type="success" round @click="handleRegister" v-else>注册</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang='less' scoped>
.LoginView {
  width: 100vw;
  height: 100vh;
  display: flex;
  user-select: none;

  #login_left {
    height: 100%;
    flex: 1;
    background: url(https://gw.alipayobjects.com/zos/rmsportal/TVYTbAXWheQpRcWDaDMu.svg) repeat 0 0;
  }

  #login_right {
    width: 700px;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    #login_item {
      position: relative;
      height: 500px;
      width: 500px;
      // border: 1px solid var(--el-color-primary);
      box-shadow: 0 2px 4px rgba(0, 0, 0, .3);
      border: 1px solid rgba(235, 235, 235, .38);
      border-radius: 4px;
      // background-image: url('/img/zy_zuo.png'), url('/img/zy_you.png');
      // background-repeat: no-repeat, no-repeat;
      // background-position: 0 100%, 100% 100%;
      // background-size: 20%;
      padding: 50px;

      .login_welcom {
        // height: 130px;
        // line-height: 130px;
        font-size: 27px;
        text-align: center;
        letter-spacing: 3px;
        animation: logoAnimation .5s ease;
        // animation-delay: .3s;
        color: var(--el-text-color-primary);
        font-family: '钉钉进步体';
      }

      @keyframes logoAnimation {
        0% {
          opacity: 0;
          transform: translateY(-50px);
        }

        100% {
          opacity: 1;
          transform: translateY(0);
        }
      }

      .login_change {
        margin-top: 10px;
        margin-bottom: 15px;
        width: 100%;
        display: flex;

        .change_item {
          flex: 1;
          text-align: center;
          font-size: 16px;
          letter-spacing: 3px;
          cursor: pointer;
          color: var(--el-text-color-primary);
          font-family: '钉钉进步体';
          animation: logoAnimation .5s ease;
          transition: opacity .3s ease;
        }
      }

      .login_form {
        .form_item {
          margin-bottom: 20px;

          .login_input {
            height: 40px;
          }
        }
      }

      .login_login {
        height: 100px;
        text-align: center;
        margin-top: 20px;
        // display: flex;
        // flex-direction: column;
        // // justify-content: space-between;
        // align-items: center;
        // justify-content: center;


        .el-button {
          margin-top: 5px;
          width: 100%;
          height: 40px;
          line-height: 40px;
          font-size: 16px;
          letter-spacing: 3px;
          animation: logoAnimation .5s ease;
        }
      }
    }

    @media screen and (max-width: 1200px) {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 90%;

      #login_item {
        border: none;
        box-shadow: none;
        padding: 20px;
      }
    }
  }

}
</style>